package com.yanq.liancar.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.CashCouponAdapter;
import com.yanq.liancar.adapter.ServiceVoucherAdapter;
import com.yanq.liancar.bean.BaseDataStringBean;
import com.yanq.liancar.bean.PayResult;
import com.yanq.liancar.bean.ServiceAliPayBean;
import com.yanq.liancar.bean.ServiceforBuyBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.WeChatPayBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PaymentActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_ServiceType)
    TextView tvServiceType;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_carType)
    TextView tvCarType;
    @BindView(R.id.tv_serviceVoucher)
    TextView tvServiceVoucher;
    @BindView(R.id.tv_moneyVoucher)
    TextView tvMoneyVoucher;
    @BindView(R.id.tv_ActualPayment)
    TextView tvActualPayment;
    @BindView(R.id.rb_wechat)
    RadioButton rbWechat;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.tv_xiadan)
    TextView tvXiadan;
    @BindView(R.id.ll_zhifu)
    LinearLayout ll_zhifu;

    private ServiceVoucherAdapter serviceVoucherAdapter;    //服务券
    private CashCouponAdapter cashCouponAdapter;            //代金券
    private int carType,serviceType;    //汽车类型
    private int payType=2;
    private List<ServiceforBuyBean.DataBean.ServiceVoucherBean> serviceVoucherList=new ArrayList<>();     //服务券
    private List<ServiceforBuyBean.DataBean.CouponBean>couponBeanList=new ArrayList<>();                  //代金券
    private ServiceforBuyBean.DataBean.CarServiceBean carServiceBean;
    private IWXAPI api;
    private static final String APP_ID="wxd2e19fc6b6f17ec0";
    private String cashcoupon_id,serviceName,service_id ,id,orderID,statu,shopid;
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**

                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。

                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtils.e("resultInfo====",resultInfo);
                    LogUtils.e("resultStatus====",resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PaymentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        RxToast.success("下单成功");
                        Bundle bundle=new Bundle();
                        bundle.putString("orderID",orderID);
                        RxActivityTool.skipActivityAndFinish(PaymentActivity.this,PurchaseSuccessActivity.class,bundle);
                    } else {

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PaymentActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

            }

        }

    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this,APP_ID);
        api.registerApp(APP_ID);
        setContentView(R.layout.activity_paymentactivity);
        Utils.setStatusBar(this, true,false);
        ButterKnife.bind(this);
        mTvTitle.setText(getIntent().getStringExtra("title")+"买单");
        shopid=getIntent().getStringExtra("id");
        serviceType=getIntent().getIntExtra("serviceType",0);

        LogUtils.e("id和serviceType===",id+"========"+serviceType);
        if (serviceType==80||serviceType==90){
            getShopDetails1();
        }else {
            getShopDetails();
        }
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb_wechat:
                        payType=2;
                        break;
                    case R.id.rb_ali:
                        payType=1;
                        break;
                }
            }
        });
        if ("精致洗车".equals(getIntent().getStringExtra("title"))){
            serviceName="精致洗车";
            statu=getIntent().getExtras().getString("statu");
            LogUtils.e("sdadasdaf",statu);
        }else if ("标准洗车".equals(getIntent().getStringExtra("title"))) {
            serviceName = "标准洗车";
        }
//        }else if ("美容养护".equals(getIntent().getStringExtra("title"))){
//            serviceType=3+"";
//            serviceName="美容养护";
//        }else if ("保养维修".equals(getIntent().getStringExtra("title"))){
//            serviceType=4+"";
//            serviceName="保养维修";
//        }else if ("钣金喷漆".equals(getIntent().getStringExtra("title"))){
//            serviceType=5+"";
//            serviceName="钣金喷漆";
//        }else if ("全车打蜡".equals(getIntent().getStringExtra("title"))){
//            serviceType=7+"";
//            serviceName="全车打蜡";
//        }
    }

    @OnClick({R.id.tv_serviceVoucher, R.id.tv_moneyVoucher, R.id.tv_pay,R.id.tv_carType,R.id.tv_xiadan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_serviceVoucher:
                if (!serviceVoucherList.isEmpty()){
                    serviceDialog(1);
                }
                break;
            case R.id.tv_moneyVoucher:
                if (!couponBeanList.isEmpty()){
                    serviceDialog(2);
                }
                break;
            case R.id.tv_pay:
                LogUtils.e("sdadasdad0",payType+"");
                if (payType==1){
                    Payment();
                }else {
                    WeChatPayment();
                }
                break;
            case R.id.tv_xiadan:
                DiscountBuy();
                break;
            case R.id.tv_carType:
                CarTypeDialog();
                break;
        }
    }


    private void CarTypeDialog(){
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.cartype_dialog, null);
        final TextView smallcar=contentView.findViewById(R.id.tv_smallcar);
        final TextView bigcar=contentView.findViewById(R.id.tv_bigcar);
        final TextView suvcar=contentView.findViewById(R.id.tv_SUVcar);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels -80;
        params.bottomMargin=20;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        //textview_border_blue_write
        smallcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carType=0;
                smallcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
                smallcar.setTextColor(getResources().getColor(R.color.white));
                bigcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                bigcar.setTextColor(getResources().getColor(R.color.main_color));
                suvcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                suvcar.setTextColor(getResources().getColor(R.color.main_color));
                tvCarType.setText("小型汽车");
                bottomDialog.dismiss();
            }
        });
        bigcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carType=1;
                smallcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                smallcar.setTextColor(getResources().getColor(R.color.main_color));
                bigcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
                bigcar.setTextColor(getResources().getColor(R.color.white));
                suvcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                suvcar.setTextColor(getResources().getColor(R.color.main_color));
                tvCarType.setText("大型汽车");
                bottomDialog.dismiss();
            }
        });
        suvcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carType=2;
                smallcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                smallcar.setTextColor(getResources().getColor(R.color.main_color));
                bigcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                bigcar.setTextColor(getResources().getColor(R.color.main_color));
                suvcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
                suvcar.setTextColor(getResources().getColor(R.color.white));
                tvCarType.setText("SUV汽车");
                bottomDialog.dismiss();
            }
        });

    }


    private void serviceDialog(int type){
        LogUtils.e("111111111========",serviceVoucherList.size()+"");
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.servicevoucher_dialog, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels -40;
        params.bottomMargin=20;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        RecyclerView recyclerView=contentView.findViewById(R.id.recyclerview);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        TextView tv_title=contentView.findViewById(R.id.tv_title);
        if (type==1){
            tv_title.setText("可使用服务券");
            serviceVoucherAdapter=new ServiceVoucherAdapter(R.layout.item_servicevoucher,serviceVoucherList);
            recyclerView.setAdapter(serviceVoucherAdapter);
            serviceVoucherAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    bottomDialog.dismiss();
                    tvServiceVoucher.setText("服务券一次抵扣");
                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.main_color));
                    ll_zhifu.setVisibility(View.GONE);
                    tvXiadan.setVisibility(View.VISIBLE);
                    if (couponBeanList.size()>0){
                        tvMoneyVoucher.setText("选择");
                    }
                    service_id=serviceVoucherList.get(position).getService_id()+"";
                    cashcoupon_id=null;
                }
            });
        }else {
            tv_title.setText("可使用代金券");
            cashCouponAdapter=new CashCouponAdapter(R.layout.item_servicevoucher,couponBeanList);
            recyclerView.setAdapter(cashCouponAdapter);
            cashCouponAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    bottomDialog.dismiss();
                    tvMoneyVoucher.setText(couponBeanList.get(position).getCashcoupon_value()+"");
                    tvMoneyVoucher.setTextColor(getResources().getColor(R.color.main_color));
                    if (carServiceBean.getServicePrice()>couponBeanList.get(position).getCashcoupon_value()){
                        tvActualPayment.setText(+carServiceBean.getServicePrice()-couponBeanList.get(position).getCashcoupon_value()+"");
                        ll_zhifu.setVisibility(View.VISIBLE);
                        tvXiadan.setVisibility(View.GONE);
                    }else {
                        ll_zhifu.setVisibility(View.GONE);
                        tvXiadan.setVisibility(View.VISIBLE);
                        tvXiadan.setText("代金券优惠买单");
                    }
                    if (serviceVoucherList.size()>0){
                        tvServiceVoucher.setText("选择");
                    }
                    cashcoupon_id=couponBeanList.get(position).getCashcoupon_id()+"";
                    service_id=null;
                }
            });
        }
    }


    //查询订单买单信息（标准洗车）
    private void getShopDetails(){
        LogUtils.e("asdasdasd",serviceType+"========="+id);
        OkGo.<String>post(Config.s + "llc/queryCarServiceForPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("id", shopid)
                .params("serviceType", serviceType)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ServiceforBuyBean serviceVoucherBean = gson.fromJson(response.body(), ServiceforBuyBean.class);
                        if (serviceVoucherBean.isIsSuccess()) {
                            if (null!=serviceVoucherBean.getData()){
                                id=serviceVoucherBean.getData().getCarService().getId()+"";
                                carServiceBean=serviceVoucherBean.getData().getCarService();
                                tvPrice.setText(carServiceBean.getServicePrice()+"");
                                tvActualPayment.setText(carServiceBean.getServicePrice()+"");
                                serviceVoucherList=serviceVoucherBean.getData().getServiceVoucher();
                                couponBeanList=serviceVoucherBean.getData().getCoupon();

                                if (!serviceVoucherList.isEmpty()){
                                    tvServiceVoucher.setText("选择");
                                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.main_color));
                                }else {
                                    tvServiceVoucher.setText("暂无");
                                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.gray));
                                    tvServiceVoucher.setEnabled(true);
                                }

                                if (!couponBeanList.isEmpty()){
                                    tvMoneyVoucher.setText("选择");
                                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.main_color));
                                }else {
                                    tvMoneyVoucher.setText("暂无");
                                    tvMoneyVoucher.setTextColor(getResources().getColor(R.color.gray));
                                    tvMoneyVoucher.setEnabled(true);
                                }
                                tvPay.setEnabled(true);
                            }else {
                                RxToast.error("暂无数据");
                            }
                        } else {
                            RxToast.error(serviceVoucherBean.getOutputMessage());
                        }
                    }
                });
    }

    //买单接口
    private void DiscountBuy(){
        OkGo.<String>post(Config.s + "llc/carServiceDownPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("servicePrice", tvActualPayment.getText().toString().trim())
                .params("cashcoupon_id", cashcoupon_id)
                .params("serviceType", serviceType)
                .params("serviceName", serviceName)
                .params("carType", carType)
                .params("service_id", service_id)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseDataStringBean baseBean=gson.fromJson(response.body(),BaseDataStringBean.class);
                        if (baseBean.isIsSuccess()){
                            RxToast.success("下单成功");
                            Bundle bundle=new Bundle();
                            bundle.putString("orderID",baseBean.getData());
                            LogUtils.e("13123131",baseBean.getData()+"");
                            RxActivityTool.skipActivityAndFinish(PaymentActivity.this,PurchaseSuccessActivity.class,bundle);
                        }else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    //查询订单买单信息（精致洗车）
    private void getShopDetails1(){
        OkGo.<String>post(Config.s + "llc/fineCarServerController/queryFineCarServerForPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("type", serviceType)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ServiceforBuyBean serviceVoucherBean = gson.fromJson(response.body(), ServiceforBuyBean.class);
                        if (serviceVoucherBean.isIsSuccess()) {
                            if (null!=serviceVoucherBean.getData()){
                                //id=serviceVoucherBean.getData().getCarService().getId()+"";
                                carServiceBean=serviceVoucherBean.getData().getCarService();
                                tvPrice.setText(carServiceBean.getServicePrice()+"");
                                tvActualPayment.setText(carServiceBean.getServicePrice()+"");
                                serviceVoucherList=serviceVoucherBean.getData().getServiceVoucher();
                                couponBeanList=serviceVoucherBean.getData().getCoupon();

                                if (!serviceVoucherList.isEmpty()){
                                    tvServiceVoucher.setText("选择");
                                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.main_color));
                                }else {
                                    tvServiceVoucher.setText("暂无");
                                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.gray));
                                    tvServiceVoucher.setEnabled(true);
                                }

                                if (!couponBeanList.isEmpty()){
                                    tvMoneyVoucher.setText("选择");
                                    tvServiceVoucher.setTextColor(getResources().getColor(R.color.main_color));
                                }else {
                                    tvMoneyVoucher.setText("暂无");
                                    tvMoneyVoucher.setTextColor(getResources().getColor(R.color.gray));
                                    tvMoneyVoucher.setEnabled(true);
                                }

                                tvPay.setEnabled(true);

                            }else {
                                RxToast.error("暂无数据");
                            }
                        } else {
                            RxToast.error(serviceVoucherBean.getOutputMessage());
                        }
                    }
                });
    }

    //支付宝支付
    private void Payment(){
        OkGo.<String>post(Config.s + "llc/carServiceAliPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("servicePrice", tvPrice.getText().toString().trim())
                .params("cashcoupon_id", cashcoupon_id)
                .params("serviceType", serviceType)
                .params("serviceName", serviceName)
                .params("carType", carType)
                .params("service_id", service_id)
                .params("shopId", shopid)
                .params("allPrice", tvActualPayment.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        final ServiceAliPayBean baseBean=gson.fromJson(response.body(),ServiceAliPayBean.class);
                        if (baseBean.isIsSuccess()){
                            final String info= baseBean.getData().getSigned_content();
                            LogUtils.e("加签info===",info);
                            if ("".equals(info)||!TextUtils.isEmpty(info)){
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(PaymentActivity.this);
                                        Map<String, String> result = alipay.payV2(info, true);

                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        mHandler.sendMessage(msg);
                                        orderID=baseBean.getData().getOnum();
                                        LogUtils.e("13123131",baseBean.getData().getOnum()+"");
                                    }
                                };
                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            }
                        }else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }
                });
    }

    //微信支付
    private void WeChatPayment(){
        OkGo.<String>post(Config.s + "llc/carServiceWXPay")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("servicePrice",tvActualPayment.getText().toString().trim())
                .params("cashcoupon_id",cashcoupon_id)
                .params("serviceType", serviceType)
                .params("serviceName", serviceName)
                .params("carType", carType)
                .params("service_id", service_id)
                .params("shopId", shopid)
                .params("allPrice", tvActualPayment.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WeChatPayBean baseBean=gson.fromJson(response.body(),WeChatPayBean.class);
                        if (baseBean.isIsSuccess()){
                            if (baseBean.getData()!=null){
                                PayReq request = new PayReq();
                                request.appId = baseBean.getData().getAppid();
                                request.partnerId =baseBean.getData().getPartnerId();
                                request.prepayId= baseBean.getData().getPrepayId();
                                request.packageValue = baseBean.getData().getPackageValue();
                                request.nonceStr= baseBean.getData().getNonceStr();
                                request.timeStamp= baseBean.getData().getTimeStamp();
                                request.sign= baseBean.getData().getSign();
                                api.sendReq(request);
                                finish();
                                LogUtils.e(" api.sendReq=====",api.sendReq(request)+"");
                            }
                        }else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }


                });


        //        String order_id=Utils.md5(UUID.randomUUID().toString().replace("_","")+System.currentTimeMillis());
        //        Log.e("dadadassda", price.replace("¥",""));
        //        WechatPayTools.wechatPayUnifyOrder(mContext,
        //            "wxd2e19fc6b6f17ec0", //微信分配的APP_ID
        //            "1513987451", //微信分配的 PARTNER_ID (商户ID)
        //            "042732fcd9da459da435cdffba5bd01d", //微信分配的 PRIVATE_KEY (私钥)
        //            new WechatModel(order_id, //订单ID (唯一)
        //                            price.replace("¥",""), //价格
        //                        tvPayName.getText().toString().trim(), //商品名称
        //                        "qqqqqqq"), //商品描述详情
        //                                new OnSuccessAndErrorListener() {
        //        @Override
        //        public void onSuccess(String s) {
        //            RxToast.success(s);
        //        }
        //
        //        @Override
        //        public void onError(String s) {
        //            RxToast.error(s);
        //        }
        //    });

    }

}
